import json
import re
import time
import xml.etree.ElementTree as ET
from typing import Dict, Any, Optional

class MessageParser:
    """消息解析工具类"""
    
    @staticmethod
    def is_group_invite_message(message_data: dict) -> bool:
        """判断是否是群邀请消息"""
        try:
            # 检查消息类型和内容
            category = message_data.get('category', 0)
            content = message_data.get('content', '')
            
            # 群邀请消息的category通常是49
            if category != 49:
                return False
            
            # 从content的XML中提取type字段
            type_match = re.search(r'<type>(\d+)</type>', content)
            if type_match:
                msg_type = int(type_match.group(1))
                # 群邀请消息的type通常是5
                if msg_type == 5 and '邀请你加入群聊' in content:
                    return True
            
            return False
            
        except Exception as e:
            print(f"判断群邀请消息时出错: {e}")
            return False
    
    @staticmethod
    def parse_group_invite(message_data: dict) -> Optional[Dict[str, Any]]:
        """解析群邀请消息的详细信息"""
        try:
            content = message_data.get('content', '')
            print(f"开始解析群邀请消息，原始content长度: {len(content)}")
            
            # 使用XML解析器解析群邀请消息
            try:
                # 解析XML
                root = ET.fromstring(content)
                print(f"XML解析成功，根元素: {root.tag}")
                
                # 查找appmsg元素
                appmsg = root.find('appmsg')
                if appmsg is None:
                    print("❌ 未找到appmsg元素")
                    return None
                
                # 提取标题
                title_elem = appmsg.find('title')
                title = title_elem.text if title_elem is not None else ""
                print(f"提取到标题: {title}")
                
                # 提取描述信息
                des_elem = appmsg.find('des')
                des = des_elem.text if des_elem is not None else ""
                print(f"提取到描述: {des}")
                
                # 提取邀请链接
                url_elem = appmsg.find('url')
                invite_url = url_elem.text if url_elem is not None else ""
                if invite_url:
                    invite_url = invite_url.strip()
                    print(f"提取到邀请链接: {invite_url}")
                else:
                    print("⚠️ 未提取到邀请链接")
                
                # 提取缩略图URL
                thumb_elem = appmsg.find('thumburl')
                thumb_url = thumb_elem.text if thumb_elem is not None else ""
                if thumb_url:
                    thumb_url = thumb_url.strip()
                    print(f"提取到缩略图URL: {thumb_url}")
                
                # 提取消息类型
                type_elem = appmsg.find('type')
                msg_type = type_elem.text if type_elem is not None else ""
                print(f"提取到消息类型: {msg_type}")
                
                # 提取动作类型
                action_elem = appmsg.find('action')
                action = action_elem.text if action_elem is not None else ""
                print(f"提取到动作类型: {action}")
                
                # 提取显示类型
                showtype_elem = appmsg.find('showtype')
                showtype = showtype_elem.text if showtype_elem is not None else ""
                print(f"提取到显示类型: {showtype}")
                
            except ET.ParseError as e:
                print(f"❌ XML解析失败: {e}")
                return None
            except Exception as e:
                print(f"❌ XML处理出错: {e}")
                return None
            
            # 从描述中提取群名称和邀请人（这部分仍使用正则表达式，因为描述是CDATA内容）
            group_name = "未知群"
            inviter_nickname = "未知用户"
            
            if des:
                # 提取群名称 - 格式："xxx"邀请你加入群聊"群名"
                group_match = re.search(r'邀请你加入群聊"([^"]+)"', des)
                if group_match:
                    group_name = group_match.group(1)
                    print(f"提取到群名称: {group_name}")
                
                # 提取邀请人昵称 - 格式："邀请人"邀请你加入群聊
                inviter_match = re.search(r'"([^"]+)"邀请你加入群聊', des)
                if inviter_match:
                    inviter_nickname = inviter_match.group(1)
                    print(f"提取到邀请人: {inviter_nickname}")
            
            # 构建返回结果
            result = {
                'title': title,
                'description': des,
                'group_name': group_name,
                'inviter_nickname': inviter_nickname,
                'invite_url': invite_url,
                'thumb_url': thumb_url,
                'msg_type': msg_type,
                'action': action,
                'showtype': showtype,
                'msg_id': message_data.get('msgId', 0),
                'timestamp': message_data.get('timestamp', ''),
                'sender_id': message_data.get('sender', {}).get('id', ''),
                'sender_nickname': message_data.get('sender', {}).get('nickname', ''),
                'raw_content': content  # 保存原始XML内容
            }
            
            print(f"✅ 群邀请消息解析完成:")
            print(f"   群名称: {group_name}")
            print(f"   邀请人: {inviter_nickname}")
            print(f"   邀请链接: {invite_url}")
            print(f"   消息ID: {result['msg_id']}")
            print(f"   消息类型: {msg_type}")
            print(f"   动作类型: {action}")
            
            return result
            
        except Exception as e:
            print(f"❌ 解析群邀请信息时出错: {e}")
            return None
    
    @staticmethod
    def parse_message(message) -> Optional[Dict[str, Any]]:
        """解析消息数据"""
        try:
            # 检查消息是否为空
            if not message or message == "":
                print("消息为空")
                return None
            
            # 解析JSON消息
            if isinstance(message, str):
                # 检查是否是有效的JSON字符串
                message = message.strip()
                if not message:
                    print("消息字符串为空")
                    return None
                    
                try:
                    message_data = json.loads(message)
                except json.JSONDecodeError as e:
                    print(f"消息JSON解析失败: {e}")
                    print(f"消息内容: {message[:100]}...")  # 显示前100个字符
                    return None
            else:
                message_data = message
            
            return message_data
            
        except Exception as e:
            print(f"解析消息时出错: {e}")
            return None

class MessageProcessor:
    """消息处理工具类"""
    
    @staticmethod
    def process_group_invite(user_name: str, message_data: dict) -> Optional[Dict[str, Any]]:
        """处理群邀请消息"""
        try:
            # 解析群邀请信息
            invite_info = MessageParser.parse_group_invite(message_data)
            if not invite_info:
                print(f"解析群邀请信息失败 - {user_name}")
                return None
            
            print(f"收到群邀请消息 - {user_name}")
            print(f"群名称: {invite_info['group_name']}")
            print(f"邀请人: {invite_info['inviter_nickname']}")
            print(f"消息ID: {invite_info['msg_id']}")
            
            # 添加接收时间
            invite_info['received_time'] = time.strftime('%Y-%m-%d %H:%M:%S')
            
            return invite_info
            
        except Exception as e:
            print(f"处理群邀请时出错 - {user_name}: {e}")
            return None
    
    @staticmethod
    def build_invite_reply(user_name: str, invite_info: dict, action: str = "accept") -> Dict[str, Any]:
        """构建群邀请回复消息"""
        try:
            reply_message = {
                "action": "reply_group_invite",
                "user_name": user_name,
                "msg_id": invite_info.get('msg_id', 0),
                "reply_type": action,  # "accept" 或 "reject"
                "title": invite_info.get('title', ''),
                "description": invite_info.get('description', ''),
                "group_name": invite_info['group_name'],
                "inviter_nickname": invite_info['inviter_nickname'],
                "invite_url": invite_info.get('invite_url', ''),
                "thumb_url": invite_info.get('thumb_url', ''),
                "msg_type": invite_info.get('msg_type', ''),
                "timestamp": invite_info['timestamp'],
                "sender_id": invite_info.get('sender_id', ''),
                "sender_nickname": invite_info.get('sender_nickname', '')
            }
            
            return reply_message
            
        except Exception as e:
            print(f"构建群邀请回复时出错 - {user_name}: {e}")
            return {}

class MessageValidator:
    """消息验证工具类"""
    
    @staticmethod
    def validate_message_format(message_data: dict) -> bool:
        """验证消息格式是否正确"""
        try:
            required_fields = ['category', 'content', 'msgId', 'timestamp']
            for field in required_fields:
                if field not in message_data:
                    print(f"消息缺少必需字段: {field}")
                    return False
            
            return True
            
        except Exception as e:
            print(f"验证消息格式时出错: {e}")
            return False
    
    @staticmethod
    def validate_group_invite_content(content: str) -> bool:
        """验证群邀请消息内容格式"""
        try:
            # 检查是否包含必要的XML标签
            required_tags = ['<title>', '<des>', '<url>']
            for tag in required_tags:
                if tag not in content:
                    print(f"群邀请消息缺少必需标签: {tag}")
                    return False
            
            return True
            
        except Exception as e:
            print(f"验证群邀请内容时出错: {e}")
            return False

# 创建全局实例
message_parser = MessageParser()
message_processor = MessageProcessor()
message_validator = MessageValidator() 